package com.xinghai.web.manager;

import cn.hutool.core.util.ReUtil;
import com.xinghai.web.common.ErrorCode;
import com.xinghai.web.constant.CommonConstant;
import com.xinghai.web.exception.BusinessException;
import com.xinghai.web.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmailManager {

    @Resource
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private UserMapper userMapper;

    @Resource
    private JavaMailSenderImpl javaMailSender;

    private static final List<String> ALLOWED_EMAIL_SUFFIXES = Arrays.asList("@qq.com", "@163.com");


    /**
     * 发送文本邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     */

    public boolean sendSimpleMail(String to, String subject, String content){
        Integer result = userMapper.selectAllByEmail(to);
        if (!validMail(to)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"禁止非法格式邮箱");
        }
        if (subject.startsWith("注册", 4)&&result>0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"邮箱已注册过账号");
        }
        if (subject.startsWith("修改", 4)&&result<1) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"邮箱未注册");
        }
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String sendtime = ops.get(CommonConstant.NAME + ":" + "sendtime" + ":" + to);
        if (sendtime == null) sendtime = "";
        if (sendtime.equals("1")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "一分钟只能发送一次");
        }
        SimpleMailMessage message = new SimpleMailMessage();
        message.setText(content + "，有效时间为五分钟");
        message.setTo(to);
        message.setSubject(subject);
        if (ReUtil.isMatch("^[0-9]+@qq.com$", to)) {
            message.setFrom(from);
        }
        if (ReUtil.isMatch("^[0-9a-zA-Z]+@163.com$", to)) {
            javaMailSender.setHost("smtp.163.com");
            javaMailSender.setUsername("a2540155530@163.com");
            javaMailSender.setPassword("WIEHYEQBBJEWURPO");
            javaMailSender.setPort(553);
            message.setFrom("a2540155530@163.com");
        }
        try {
            mailSender.send(message);
            ops.set(CommonConstant.NAME + ":" + "sendtime" + ":" + to, "1");
            if (subject.startsWith("修改", 4)) {
                //发送验证码前先删除前面遗留的
                redisTemplate.delete(CommonConstant.NAME + ":" + "changepwdcode" + ":" + to);
                ops.set(CommonConstant.NAME + ":" + "changepwdcode" + ":" + to, content);
            }
            redisTemplate.delete(CommonConstant.NAME + ":" + "registercode" + ":" + to);
            ops.set(CommonConstant.NAME + ":" + "registercode" + ":" + to, content);
            redisTemplate.expire(CommonConstant.NAME + ":" + "registercode" + ":" + to, 5, TimeUnit.MINUTES);
            redisTemplate.expire(CommonConstant.NAME + ":" + "sendtime" + ":" + to, 1, TimeUnit.MINUTES);
            redisTemplate.expire(CommonConstant.NAME + ":" + "changepwdcode" + ":" + to, 5, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            log.info("邮箱发送失败:{}", to);
            return false;
        }
    }

    public boolean validMail(String mail){
        int i = mail.indexOf("@");
        String mailSuffix = mail.substring(i);
        return !StringUtils.isEmpty(mail) && ALLOWED_EMAIL_SUFFIXES.contains(mailSuffix);
    }
}



